<template>
  <lazy-load v-bind="view" @command="onCommand" />
</template>
<script lang="ts" setup>
  import { Command, CommandOptions, Feedback, View } from '../core';
  import { ref, shallowRef, watchEffect } from 'vue';
  import { ElEmpty } from 'element-plus';
  import LazyLoad from './LazyLoad.vue';
  import { Row } from '../elementUI';

  const EmptyView: View = {
    view: ElEmpty,
    imageSize: 200
  };

  const props = defineProps<{
    captureEmptyLayer?: boolean;
    layer?: string;
    command: CommandOptions;
    row?: Row;
  }>();

  const loading = ref(true);

  const view = shallowRef<View>(EmptyView);

  async function onCommand(command: CommandOptions, row?: Row) {
    if (!command) return;

    if (command.layer && command.layer !== props.layer) return;

    if (!command.layer && !props.captureEmptyLayer) return;

    // 刷新
    if (command.directive === 'refresh') {
      await refresh(props.command, row || props.row);
      return;
    }

    // 跳转
    if (command.directive === 'redirect') {
      await refresh({ ...command, directive: undefined }, row);
      return;
    }

    // 执行
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const r: Feedback = (await Command.invoke(command, row)) as Feedback;

    if (!r?.directive) return;

    if (r.directive === 'refresh') {
      await refresh(props.command, props.row);
      return;
    }

    if (r.directive === 'redirect') {
      await refresh({ ...r, directive: undefined }, r.row);
    }
  }

  async function refresh(command: CommandOptions, row?: Row) {
    loading.value = true;
    view.value = EmptyView;
    try {
      if (command.url) {
        view.value = (await Command.invoke(command, row)) as View;
      }
    } catch (e) {
    } finally {
      loading.value = false;
    }
  }

  watchEffect(async () => {
    await refresh(props.command, props.row);
  });
</script>
